# coding:utf-8
import re

from bson import ObjectId
from flask import request, jsonify
from flask_restful import Resource
from jieba import analyse
from snownlp import SnowNLP

from app import api
from config import basepath
from dao.ArticleDao import addSentiment
from sentiment import userDict
from sentiment.word_cloud.wordCloud import worldcloud
from sentiment.word_freq.wordFreq import word_freq


class ArticleController(Resource):
    '''
    文章情感分析：贝叶斯分析
    1）断句
    2）分析,逐句分析，分数累加
    3）保存到数据库{keywords:[],sentiment:{pos:10,neg:20},wordFreq:[{'生活': 6}, {'一种': 5}, ]}
    4) 词云：http://localhost:8088/images/wordcloud
    '''

    def post(self):
        id = request.form.get('id')
        text = request.form.get('text')
        # try:
        # keywords
        keywords = analyse.extract_tags(text, topK=10, allowPOS=('ns'))
        # sentiment
        sentences = re.split('[。！~？!?…]', text)
        pos = 0
        neg = 0
        for s in sentences:
            if len(s) <2:
                continue
            pos_score = SnowNLP(s).sentiments
            pos += pos_score
            neg += (1 - pos_score)
        # pos = SnowNLP(text).sentiments
        # neg = 1- pos
        wordFreq = word_freq(text, 12)
        addSentiment(id, keywords, {'pos':pos,'neg':neg}, wordFreq)
        # 词云
        imgPath = basepath + '/app/static/images/wordcloud/'+id+'.png';
        worldcloud(text, imgPath)
        return {
            'code': 0
        }
        # except :
        #     print('服务器异常')
        #     return {
        #         "code":1,
        #         "msg":"服务器异常"
        #     }



api.add_resource(ArticleController, '/sentiment/article')
